<template>
  <div class="nstd-tree" style="display: flex; flex-direction: column">
    <el-input
      placeholder="请输入内容"
      v-model="seachVal"
      class="input-with-select"
      size="mini"
      clearable
      v-specialChar
      maxlength="100"
    >
      <el-button slot="append" icon="el-icon-search" size="mini" @click="search()">搜索</el-button>
    </el-input>
    <div style="display: flex; align-items: center" v-if="['1', '2'].includes(treeType) && !noStatus">
      <el-checkbox-group class="checkbox-group" v-model="inLine" @change="search()">
        <el-checkbox :label="0">离线</el-checkbox>
        <el-checkbox :label="1">在线</el-checkbox>
      </el-checkbox-group>
      <el-checkbox label="1" v-model="follow" style="margin-left: 30px" @change="search()">关注</el-checkbox>
    </div>
    <el-scrollbar style="height: 100%">
      <el-tree
        ref="tree"
        accordion
        class="tree"
        default-expand-all
        :data="treeData"
        node-key="id"
        :props="defaultProps"
        highlight-current
        @node-click="handleNodeClick"
        :load="loadNodeData"
        lazy
      >
        <span slot-scope="{ node, data }" class="tree-box-content">
          <el-tooltip class="item" effect="dark" :content="data.name" placement="top-end">
            <div class="tree-item">
              <img
                class="star"
                :src="starNull"
                alt=""
                v-if="
                  !noStatus &&
                  data.subNode &&
                  data.subNode.length === 0 &&
                  data.level !== 20 &&
                  data.follow === 0 &&
                  ['1', '2'].includes(treeType)
                "
                @click.stop="patrolDeviceFollow(data, node)"
              />
              <img
                class="star"
                :src="star"
                alt=""
                v-if="
                  !noStatus &&
                  data.subNode &&
                  data.subNode.length === 0 &&
                  data.level !== 20 &&
                  data.follow === 1 &&
                  ['1', '2'].includes(treeType)
                "
                @click.stop="delPatrolDeviceFollow(data, node)"
              />
              <span class="tree-name"
                >{{ data.name
                }}<span
                  v-if="data.level === 200"
                  v-text="`【在线${data.onlineCount}台；离线${data.offlineCount}台】`"
                ></span
              ></span>
              <span
                class="tree-name"
                v-if="
                  data.subNode &&
                  data.subNode.length === 0 &&
                  data.level !== 20 &&
                  ['1', '2'].includes(treeType) &&
                  data.inLine !== null
                "
                >【{{ data.inLine ? '在线' : '离线' }}】</span
              >
              <img
                :style="{ filter: `contrast(${data.inLine ? 1 : 0.2})` }"
                class="camera"
                v-if="
                  data.subNode &&
                  data.subNode.length === 0 &&
                  data.level !== 20 &&
                  ['1', '2'].includes(treeType) &&
                  data.inLine !== null
                "
                :src="pointStatusImgObj1[data.type] || pointStatusImgObj2[data.useMode] || camera"
              />
            </div>
          </el-tooltip>
        </span>
      </el-tree>
    </el-scrollbar>
  </div>
</template>
<script>
  // import { mapGetters } from 'vuex'
  import {
    stationTree,
    patrolDeviceTreeV3,
    securityZoneTree,
    carouselPlanTree,
    patrolDeviceFollow,
    delPatrolDeviceFollow
  } from '@/api/inspect.js';
  import debounce from 'lodash.debounce';
  export default {
    name: 'NstdBizTree',
    props: {
      noStatus: {
        type: Boolean,
        default: false
      },
      // 1: 设备树；2、防区树；3、轮巡方案
      treeType: {
        type: String,
        default: '1'
      },
      defaultProps: {
        type: Object,
        default: () => {
          return {
            children: 'subNode',
            label: 'name'
          };
        }
      }
    },
    data() {
      return {
        carouselPlanParams: {
          name: '',
          stationCode: '',
          userId: ''
        },
        patrolDeviceParams: {
          dataTypes: [1],
          follow: '',
          inLine: '',
          name: '',
          stationCode: '',
          userId: ''
        },
        securityZoneParams: {
          dataTypes: [1],
          follow: '',
          inLine: '',
          name: '',
          stationCode: '',
          userId: ''
        },
        seachVal: '',
        inLine: [],
        follow: '',
        treeData: [],
        starNull: '@/assets/icon/star-null.png',
        star: import('@/assets/icon/star.png'),
        camera: import('@/assets/images/intelligentInspection/jiqiren.png'),
        userInfo: {},
        defaultExpandedKeys: [],
        pointStatusImgObj1: {
          1: import('@/assets/images/intelligentInspection/lcjqr.png'),
          2: import('@/assets/images/intelligentInspection/lcjqr.png'),
          3: import('@/assets/images/intelligentInspection/ggjqr.png'),
          13: import('@/assets/images/intelligentInspection/wurenji.png'),
          15: import('@/assets/images/intelligentInspection/jichao.png')
        },
        pointStatusImgObj2: {
          // '10': import('@/assets/icon/camera.png'),
          10: import('@/assets/images/intelligentInspection/jiqiren.png'),
          11: import('@/assets/images/intelligentInspection/qiuji.png'),
          12: import('@/assets/images/intelligentInspection/yuntai.png')
        }
      };
    },
    watch: {
      treeType() {
        // this.search()
        this.initTree();
      }
    },
    computed: {
      stationCode() {
        return this.$store.state.station.stationInfo.stationCode;
      }
      // ...mapGetters({
      //   // stationCode: 'station/stationCode',
      //   voltageLevelCode: 'station/voltageLevelCode'
      // })
    },
    mounted() {
      // this.userInfo = JSON.parse(localStorage.getItem('userInfo'));
      // this.patrolDeviceParams.userId = this.userInfo.id || '';
      // this.patrolDeviceParams.stationCode = this.stationCode || '';
      // this.securityZoneParams.userId = this.userInfo.id || '';
      // this.securityZoneParams.stationCode = this.stationCode || '';
      // this.carouselPlanParams.userId = this.userInfo.id || '';
      // this.carouselPlanParams.stationCode = this.stationCode || '';
      this.initTree();
      // this.defaultExpandedKeys.push(this.voltageLevelCode);
      // this.defaultExpandedKeys.push(this.stationCode);
    },
    methods: {
      dbClick() {
        console.log('双击');
        return false;
      },
      async initTree() {
        // this.defaultExpandedKeys = []
        const params = {};
        const { code, data } = await stationTree(params);
        if (code !== 200 || !data) {
          this.$message.error('获取设备树失败！');
          return;
        }
        this.treeData = data;
        // if(this.treeType === '1'){
        this.$nextTick(() => {
          this.$refs.tree.setCurrentKey(this.voltageLevelCode);
          this.$refs.tree.setCurrentKey(this.stationCode);
          // this.$refs.tree.$el.scrollIntoView()
        });
        // }
      },
      // 巡检设备树V3
      async patrolDeviceTreeV3() {
        const { code, data } = await patrolDeviceTreeV3(this.patrolDeviceParams);
        if (code !== 200 || !data) {
          this.$message.error('获取设备树失败！');
          return;
        }
        return data;
      },

      // 防区树
      async securityZoneTree() {
        const params = this.securityZoneParams;
        const { code, data } = await securityZoneTree(params);
        if (code !== 200 || !data) {
          this.$message.error('获取防区树失败！');
          return;
        }
        return data;
      },

      // 轮播方案树
      async carouselPlanTree() {
        const params = this.carouselPlanParams;
        console.log(params, 'params');
        const { code, data } = await carouselPlanTree(params);
        if (code !== 200 || !data) {
          this.$message.error('获取轮播方案树失败！');
          return;
        }
        return data;
      },
      // 树节点点击
      handleNodeClick: debounce(async function (data, node) {
        console.log(node, 'node');
        // if(node.expanded === false) return false
        const stationInfo = {
          stationCode: '',
          stationName: '',
          voltageLevelCode: '',
          voltageLevelName: ''
        };

        if (data.level === 20) {
          // node.loaded = false
          // node.data.subNode = []
          // node.expand()
          // node.expanded = true
          stationInfo.stationCode = data.id;
          stationInfo.stationName = data.name;
          stationInfo.voltageLevelCode = node.parent.data.id;
          stationInfo.voltageLevelName = node.parent.data.name;
          this.$store.commit('station/SET_STATION_INFO', stationInfo);
          let subNode = [];
          const stationCode = data.id;
          if (data.subNode.length) return false;
          if (this.treeType === '1') {
            this.patrolDeviceParams.name = this.seachVal;
            this.patrolDeviceParams.stationCode = stationCode;
            this.patrolDeviceParams.follow = this.follow ? 1 : '';
            this.patrolDeviceParams.inLine = this.inLine.length === 1 ? Number(this.inLine.join()) : '';
            subNode = await this.patrolDeviceTreeV3();
          } else if (this.treeType === '2') {
            this.securityZoneParams.name = this.seachVal;
            this.securityZoneParams.stationCode = stationCode;
            this.securityZoneParams.follow = this.follow ? 1 : '';
            this.securityZoneParams.inLine = this.inLine.length === 1 ? Number(this.inLine.join()) : '';
            subNode = await this.securityZoneTree();
          } else if (this.treeType === '3') {
            this.carouselPlanParams.name = this.seachVal;
            this.carouselPlanParams.stationCode = stationCode;
            subNode = await this.carouselPlanTree();
          }
          this.$nextTick(() => {
            this.$refs.tree.updateKeyChildren(stationCode, subNode);
          });
        }
        if ([201, 302].includes(data.level)) {
          stationInfo.stationCode = data.stationCode;
          stationInfo.stationName = data.stationName;
          stationInfo.voltageLevelCode = data.voltageLevel;
          this.getDicts('volt_level').then((response) => {
            const voltageLevelData = response.data.filter((item) => Number(item.dictValue) === data.voltageLevel);
            stationInfo.voltageLevelName = voltageLevelData[0].dictLabel;
            this.$store.commit('station/SET_STATION_INFO', stationInfo);
          });
        }
        if (data.level === 10) {
          stationInfo.stationCode = data.id;
          stationInfo.stationName = data.name;
          stationInfo.voltageLevelCode = '';
          stationInfo.voltageLevelName = '';
          this.$store.commit('station/SET_STATION_INFO', stationInfo);
        }
        this.$emit('node-click', {
          ...data,
          ...stationInfo
        });
      }, 500),
      // 树节点懒加载
      async loadNodeData(node, resolve) {
        const res = node.data;
        console.log(res, 'res');
        if (res.level === 20) {
          // this.stationCode = res.id
          let subNode = [];
          if (this.treeType === '1') {
            this.patrolDeviceParams.name = this.seachVal;
            this.patrolDeviceParams.stationCode = res.level === 20 ? res.id : '';
            subNode = await this.patrolDeviceTreeV3(this.patrolDeviceParams);
          } else if (this.treeType === '2') {
            this.securityZoneParams.name = this.seachVal;
            this.securityZoneParams.stationCode = res.level === 20 ? res.id : '';
            subNode = await this.securityZoneTree(this.securityZoneParams);
          } else if (this.treeType === '3') {
            this.carouselPlanParams.name = this.seachVal;
            this.carouselPlanParams.stationCode = res.level === 20 ? res.id : '';
            subNode = await this.carouselPlanTree(this.carouselPlanParams);
          }
          resolve(subNode);
        } else {
          resolve(res.subNode || []);
        }
      },
      async search(stationCode = this.stationCode) {
        const currentNode = this.$refs.tree.getCurrentNode();
        if (currentNode && currentNode.level === 10) {
          return this.initTree();
        }
        console.log(stationCode, 'stationCode');
        this.initTree();
        let subNode = [];
        if (this.treeType === '1') {
          this.patrolDeviceParams.name = this.seachVal;
          this.patrolDeviceParams.stationCode = stationCode;
          this.patrolDeviceParams.follow = this.follow ? 1 : '';
          this.patrolDeviceParams.inLine = this.inLine.length === 1 ? Number(this.inLine.join()) : '';
          subNode = await this.patrolDeviceTreeV3();
        } else if (this.treeType === '2') {
          this.securityZoneParams.name = this.seachVal;
          this.securityZoneParams.stationCode = stationCode;
          this.securityZoneParams.follow = this.follow ? 1 : '';
          this.securityZoneParams.inLine = this.inLine.length === 1 ? Number(this.inLine.join()) : '';
          subNode = await this.securityZoneTree();
        } else if (this.treeType === '3') {
          this.carouselPlanParams.name = this.seachVal;
          this.carouselPlanParams.stationCode = stationCode;
          subNode = await this.carouselPlanTree();
        }
        this.$nextTick(() => {
          this.$refs.tree.updateKeyChildren(stationCode, subNode);
        });
      },
      // 新增关注
      async patrolDeviceFollow(item, node) {
        const stationCode = node.parent.data.id;
        const params = {
          patroldeviceCode: item.id,
          stationCode: stationCode,
          userId: this.userInfo.id || ''
        };
        const { code } = await patrolDeviceFollow(params);
        if (code !== 200) {
          this.$message.error('关注失败！');
          return;
        }
        this.search(stationCode);
        // this.$message.success('关注成功！')
      },
      // 取消关注
      async delPatrolDeviceFollow(item, node) {
        const stationCode = node.parent.data.id;
        const params = {
          patroldeviceCode: item.id,
          stationCode: stationCode,
          userId: this.userInfo.id || ''
        };
        const { code } = await delPatrolDeviceFollow(params);
        if (code !== 200) {
          this.$message.error('取消关注失败！');
          return;
        }
        this.search(stationCode);
        // this.$message.success('取消关注成功！')
      }
    }
  };
</script>
<style lang="less" scoped>
  .tree-item {
    display: flex;
    align-items: center;
    .star {
      width: 12px;
      height: 12px;
      margin-right: 4px;
    }
    .camera {
      width: 14px;
      height: 12px;
    }
  }
  ::v-deep .el-input-group__append {
    background-color: #1dd4e7 !important;
  }
  ::v-deep .el-button:hover {
    background-color: none !important;
  }
  ::v-deep .el-button--default:hover {
    background-color: none !important;
  }
  .nstd-tree {
    width: 100%;
    height: 100%;
    /deep/ .el-scrollbar__view {
      height: 100%;
    }
    .el-tree {
      height: 100%;
    }
  }
  .checkbox-group {
    margin-top: 4px;
  }
  .tree-name {
    font-family:
      PingFangSC,
      PingFang SC;
    font-weight: 400;
    font-size: 12px;
    color: #ffffff;
    line-height: 17px;
    text-align: left;
    font-style: normal;
  }

  .tree1 {
    /deep/ .el-tree-node__content {
      background-color: unset !important;
      font-size: 16px;
    }

    /deep/ .el-tree-node__expand-icon {
      display: block;
    }

    /deep/ .el-tree > .el-tree-node:after {
      border-top: inLine-block;
    }

    /deep/ .el-tree-node {
      position: relative;
      padding-left: 8px;
    }

    /deep/ .el-tree-node__children {
      padding-left: 8px;
    }

    /deep/ .el-tree-node :last-child:before {
      height: 32px;
    }

    /deep/ .el-tree > .el-tree-node:before {
      border-left: none;
    }

    /deep/ .el-tree-node:before {
      content: '';
      left: 4px;
      position: absolute;
      right: auto;
      border-width: 1px;
    }

    /deep/ .el-tree-node:after {
      content: '';
      left: 4px;
      position: absolute;
      right: auto;
      border-width: 1px;
    }

    /deep/ .el-tree-node:before {
      border-left: 1px dashed #b1daff;
      bottom: 0;
      height: 100%;
      top: -20px;
      width: 1px;
    }

    /deep/ .el-tree-node:after {
      border-top: 1px dashed #b1daff;
      height: 20px;
      top: 12px;
      width: 10px;
    }

    .tree-box-content i {
      color: #4377bf;
    }

    .tree-box-content:hover {
      background: #5293ee;
    }
  }
  .el-tree {
    min-width: 100%;
    overflow: auto;
  }

  /deep/ .el-tree-node {
    width: fit-content;
    min-width: 100%;
    & > .el-tree-node__children {
      overflow: visible;
    }
  }
</style>
